<?php
/*-------------------------------------------------------------------------\
|
|  ========================================================
|  Fusion Registry GPL
|  Copyright (C) 2007 Fusion Scripts
|
|  This program is free software; you can redistribute it and/or
|  modify it under the terms of the GNU General Public License
|  as published by the Free Software Foundation; either version 2
|  of the License, or (at your option) any later version.
|
|  This program is distributed in the hope that it will be useful,
|  but WITHOUT ANY WARRANTY; without even the implied warranty of
|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
|  GNU General Public License for more details.
|
|  You should have received a copy of the GNU General Public License
|  along with this program; if not, write to the Free Software
|  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
|  ========================================================
|
|  Email: info@fusionscripts.com
|  Web-Site: http://www.fusionscripts.com/
|
|  $Id: item.php 4 2008-08-03 01:43:03Z registry.fusion $
|
\-------------------------------------------------------------------------*/

/**
 * 'item' class for the Fusion Registry.
 *
 * @package Fusion Registry
 * @version $Id: item.php 4 2008-08-03 01:43:03Z registry.fusion $
 */

/**
 * Fusion Registry core require
 */
require_once(REGISTRY_PATH.'/lib/core.php');

/**
 * Class 'registry_item' is in charge of the major objects listed in the Fusion Registry.
 *
 * Note: 'items' were formally known as 'vehicles'.
 * This class should be invoked by the parent integration harness.
 * Most functions of this class do not have return values, instead the
 * redirect function is called to print a pretty thank you message to the
 * end user and stops the procedural code.
 *
 * @package Fusion Registry
 */
class registry_item
{
    var $ipsclass;

    /**#@+ @var string */
    var $output     = "";
    var $page_title = "";
    /**#@-*/

    /**#@+ @var array */
    var $data            = array();
    var $registry_config = array();
    var $nav_bar         = array();
    var $html            = array( 'core', 'gallery', 'item' );
    var $lib             = array( 'custom_fields', 'functions', 'upload', 'parser', 'ratings' );
    /**#@-*/

    /** @var object Fusion Registry core */
    var $core = "";

    /**
     * Invoked from parent harness, this executes the code.
     *
     * This is the only function which should be called from the harness.
     * This function is the traffic cop for this class, it should
     * do very little procedural code, if any.
     *
     * @param string $param Function to call
     */
    function auto_run($param='')
    {
        // Initialize core
        $this->core = new registry_core();
        $this->core->ipsclass =& $this->ipsclass;
        $this->core->auto_run(&$this);

        // Setup parser
        $this->lib['parser']->parse_smilies = $this->registry_config['allow_bbcode_car'];
        $this->lib['parser']->parse_bbcode  = $this->registry_config['allow_bbcode_car'];
        $this->lib['parser']->parse_html    = $this->registry_config['allow_html_car'];
        $this->lib['parser']->parse_nl2br   = 1;

        // Start our Nav Bar
        $this->nav_bar[] = "<a href='{$this->ipsclass->base_url}autocom=".REGISTRY_URL."'>".$this->ipsclass->lang['title']."</a>";

        // Which way to go?
        switch( $param )
        {
            case 'do_delete':
                $this->data['body'] = $this->do_delete();
                break;

            case 'do_modify':
                $this->data['body'] = $this->do_modify();
                break;

            case 'do_new':
                $this->data['body'] = $this->do_new();
                break;

            case 'manage_menu':
                $this->data['body'] = $this->manage_menu();
                break;

            case 'modify_menu':
                $this->data['body'] = $this->modify_menu();
                break;

            case 'new_menu':
                $this->data['body'] = $this->new_menu();
                break;

            case 'rating_menu':
                $this->data['body'] = $this->rating_menu();
                break;

            case 'do_rating':
                $this->data['body'] = $this->do_rating();
                break;

            case 'view':
            default:
                $this->data['body'] = $this->view();
                break;
        }

        // Let's create the common output elements now
        $this->data['navigation']     = $this->lib['functions']->do_navigation();
        $this->data['latest_updated'] = $this->lib['functions']->do_latest_updated();
        $this->data['my_cars']        = $this->lib['functions']->do_my_items();

        // Print it all out
        $this->output = $this->core->process_output();

        $this->ipsclass->print->add_output( $this->output );

        // Shall we use our Custom page title, or the default one?
        $this->page_title = empty($this->page_title) ? $this->ipsclass->lang['page_title'] : $this->page_title;

        // Set the title and nav bar, print the output
        $this->ipsclass->print->do_output( array( 'TITLE' => $this->ipsclass->vars['board_name'] .' -> '. $this->page_title,
                                                  'NAV'   => $this->nav_bar ) );
    }


    /**
     * Delete an item in the Fusion Registry, not undo-able
     *
     * @return string Failure returns template 'message'
     */
    function do_delete()
    {
        // For security measures we are going to make sure that the person
        // logged in is the owner of the item trying to be deleted.  So first
        // we need to select the item and find out who owns it ;)
        $this->ipsclass->DB->query( "SELECT g.*,images.attach_id, images.attach_hits, images.attach_ext,
                                        images.attach_file, images.attach_location, images.attach_thumb_location
                                     FROM ibf_registry_items AS g
                                         LEFT JOIN ibf_registry_images AS images ON images.attach_id = g.image_id
                                     WHERE g.id = '" . $this->ipsclass->input['CID'] . "'");

        $vehicle_data = $this->ipsclass->DB->fetch_row();

        // Now let's do the check
        if ( $this->ipsclass->member['id'] != $vehicle_data['member_id'] )
        {
            if ( $this->ipsclass->member['g_is_supmod'] != 1 )
            {
                // Get them outta here, they don't own this vehicle!!!
                $data = array(
                                message    => $this->ipsclass->lang['not_owner_failure'],
                                next       => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=idx",
                                next_title => $this->ipsclass->lang['main_menu'],
                             );

                // Return the message
                return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
            }
        }

        // If they are a 'supmod' and this isn't their item reset the member id
        //   for the rest of this function
        $item_owner_id = $this->ipsclass->member['id'];

        if ( ( $this->ipsclass->member['g_is_supmod'] == 1 ) AND
             ( $this->ipsclass->member['id'] != $vehicle_data['member_id'] ) )
        {
            $item_owner_id = $vehicle_data['member_id'];
        }

        // If we have made it this far let's start the deleting.
        // I smell dirty leftovers if any errors occur in this function :(

        // Let's start with the mods, let's loop through and delete the files first
        $mod_result = $this->ipsclass->DB->query("SELECT mods.image_id,images.attach_id, images.attach_hits, images.attach_location,
                                                    images.attach_ext, images.attach_file, images.attach_thumb_location
                                                  FROM ibf_registry_mods AS mods
                                                     LEFT JOIN ibf_registry_images AS images ON images.attach_id = mods.image_id
                                                  WHERE mods.item_id = '". $this->ipsclass->input['CID'] ."'
                                                    AND mods.image_id IS NOT NULL");

        // Delete the mod images one by one
        while ( $row = $this->ipsclass->DB->fetch_row($mod_result) )
        {
            // Delete highlight image from disk
            if (is_file($this->ipsclass->vars['upload_dir']."/".$row['attach_location']))
            {
                @unlink($this->ipsclass->vars['upload_dir']."/".$row['attach_location']);
            }

            // And the thumbnail
            if (is_file($this->ipsclass->vars['upload_dir']."/".$row['attach_thumb_location']))
            {
                @unlink($this->ipsclass->vars['upload_dir']."/".$row['attach_thumb_location']);
            }

            // Delete highlight image from DB
            $this->ipsclass->DB->query("DELETE FROM ibf_registry_images WHERE attach_id='". $row['attach_id'] ."'" );
        }

        // Ok, now delete the mod entries from the DB
        $this->ipsclass->DB->query("DELETE FROM ibf_registry_mods WHERE item_id = '". $this->ipsclass->input['CID'] ."' AND member_id = '" . $item_owner_id . "'");

        // Only try to delete the image if it has one
        if (!empty($vehicle_data['image_id']))
        {
            // Delete highlight image from DB
            $this->ipsclass->DB->query("DELETE FROM ibf_registry_images WHERE attach_id='". $vehicle_data['image_id'] ."'" );

            // Delete highlight image from disk
            if (is_file($this->ipsclass->vars['upload_dir']."/".$vehicle_data['attach_location']))
            {
                @unlink($this->ipsclass->vars['upload_dir']."/".$vehicle_data['attach_location']);
            }

            // And the thumbnail
            if (is_file($this->ipsclass->vars['upload_dir']."/".$vehicle_data['attach_thumb_location']))
            {
                @unlink($this->ipsclass->vars['upload_dir']."/".$vehicle_data['attach_thumb_location']);
            }
        }

        // Now let's delete any gallery images for this vehicle
        $image_query_id = $this->ipsclass->DB->query( "SELECT gallery.id, images.attach_id, images.attach_hits, images.attach_ext,
                                                            images.attach_file, images.attach_location, images.attach_thumb_location
                                                       FROM ibf_registry_images AS images
                                                            LEFT JOIN ibf_registry_gallery AS gallery ON images.attach_id = gallery.image_id
                                                            LEFT JOIN ibf_registry_items AS garage ON gallery.item_id = garage.id
                                                       WHERE garage.id = '" . $this->ipsclass->input['CID'] . "'" );

        while ( $image_data = $this->ipsclass->DB->fetch_row($image_query_id) )
        {
            // Delete images from DB
            $this->ipsclass->DB->query("DELETE FROM ibf_registry_gallery WHERE id='". $image_data['id'] ."'" );
            $this->ipsclass->DB->query("DELETE FROM ibf_registry_images WHERE attach_id='". $image_data['attach_id'] ."'" );

            // Delete highlight image from disk
            if (is_file($this->ipsclass->vars['upload_dir']."/".$image_data['attach_location']))
            {
                @unlink($this->ipsclass->vars['upload_dir']."/".$image_data['attach_location']);
            }

            // And the thumbnail
            if (is_file($this->ipsclass->vars['upload_dir']."/".$image_data['attach_thumb_location']))
            {
                @unlink($this->ipsclass->vars['upload_dir']."/".$image_data['attach_thumb_location']);
            }
        }

        // Delete any comments for this vehicle
        $this->ipsclass->DB->query("DELETE FROM ibf_registry_guestbooks WHERE item_id = '". $this->ipsclass->input['CID'] ."'");

        // Well, all looks good, let's go ahead and delete the vehicle
        $this->ipsclass->DB->query("DELETE FROM ibf_registry_items WHERE id = '". $this->ipsclass->input['CID'] ."' AND member_id = '" . $item_owner_id . "'");

        // Present message
        $this->ipsclass->print->redirect_screen( $this->ipsclass->lang['delete_car_success'], "autocom=".REGISTRY_URL."&amp;cmd=idx" );
    }


    /**
     * Update an item in the Fusion Registry
     *
     * @return string Failure returns template 'message'
     */
    function do_modify()
    {
        // For security measures we are going to make sure that the person
        //   logged in is the owner of the item trying to be modified.  So first
        //   we need to select the item and find out who owns it ;)
        // To conserve SQL calls we are piggy-backing the image lookup here.
        $this->ipsclass->DB->query( "SELECT g.*, images.attach_id, images.attach_hits, images.attach_ext,
                                        images.attach_file, images.attach_thumb_location
                                     FROM ibf_registry_items AS g
                                         LEFT JOIN ibf_registry_images AS images ON images.attach_id = g.image_id
                                     WHERE g.id = '" . $this->ipsclass->input['CID'] . "'");

        $vehicle_data = $this->ipsclass->DB->fetch_row();

        // Now let's do the check
        if ( $this->ipsclass->member['id'] != $vehicle_data['member_id'] )
        {
            if ( $this->ipsclass->member['g_is_supmod'] != 1 )
            {
                // Get them outta here, they don't own this vehicle!!!
                $data = array(
                                message     => $this->ipsclass->lang['not_owner_failure'],
                                next        => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=idx",
                                next_title  => $this->ipsclass->lang['main_menu'],
                             );

                // Return the message
                return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
            }
        }

        // Let's make sure we have all the required fields, grab all
        //  the defs first, then filter out all the ones required.
        $cf_defs = $this->lib['custom_fields']->get_cf_defs();

        $cf_required = array();

        foreach ( $cf_defs as $cf_id => $cf_row )
        {
            if ( $cf_row['field_required'] == 1 )
            {
                $cf_required[$cf_id] = $cf_row;
            }
        }

        // Compile list of missing fields (if any)
        $missing_fields = '';

        foreach ( $cf_required as $cf_id => $cf_row )
        {
            // We have to special case the make/model since they don't use the field_id as the field name
            if ( $cf_row['field_options'] == 'make' or $cf_row['field_options'] == 'model' )
            {
                if ( !isset($this->ipsclass->input[$cf_row['field_options']]) or empty($this->ipsclass->input[$cf_row['field_options']]) )
                {
                    $missing_fields .= $cf_row['field_name'] . ', ';
                }
            }
            else
            {
                if ( !isset($this->ipsclass->input[$cf_id]) or empty($this->ipsclass->input[$cf_id]) )
                {
                    $missing_fields .= $cf_row['field_name'] . ', ';
                }
            }
        }

        // If we found any report to user and bomb out
        if ( $missing_fields )
        {
            $missing_fields = substr($missing_fields, 0, -2);

            $error = preg_replace( "/<#MISSING_FIELDS#>/", $missing_fields, $this->ipsclass->lang['required_field_missing'] );

            // Sorry bud, we need/require this info!
            $data = array(
                            message    => $error,
                            next       => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=modify_item&amp;CID=".$this->ipsclass->input['CID'],
                            next_title => $this->ipsclass->lang['new_car'],
                         );

            // Return the message
            return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
        }

        // Process the custom fields input
        $cf_input = $this->lib['custom_fields']->process_cf_input($cf_defs);

        // This constructs the FIELD_NAMES and FIELD_VALUES for sql
        $db_string = $this->ipsclass->DB->compile_db_update_string( array( 'date_updated'        => time(),
                                                                           'guestbook_pm_notify' => $this->ipsclass->input['guestbook_pm_notify'],
                                                                  )      );

        // Execute the sql call
        $this->ipsclass->DB->query("UPDATE ibf_registry_items SET $db_string WHERE id = '" . $this->ipsclass->input['CID'] . "'");
        unset($db_string);

        // Now save their custom field data
        foreach ( $cf_input as $cf_id => $cf_value )
        {
            // Determine if we need to update or insert row
            $rs = $this->ipsclass->DB->query("SELECT entry_id FROM ibf_registry_field_entries WHERE item_id = '". $this->ipsclass->input['CID'] ."' AND field_id = '$cf_id'");

            $existing = $this->ipsclass->DB->fetch_row($rs);

            if ( defined($existing['entry_id']) and !empty($existing['entry_id']) )
            {
                // Update existing entry
                $db_string = $this->ipsclass->DB->compile_db_update_string( array( 'field_id' => $cf_id,
                                                                                   'item_id' => $this->ipsclass->input['CID'],
                                                                                   'field_value' => $cf_value,
                                                                          )      );

                $this->ipsclass->DB->query("UPDATE ibf_registry_field_entries SET $db_string WHERE entry_id = '". $existing['entry_id'] ."'");
            }
            else
            {
                // Insert new entry
                $db_string = $this->ipsclass->DB->compile_db_insert_string( array( 'field_id' => $cf_id,
                                                                                   'item_id' => $this->ipsclass->input['CID'],
                                                                                   'field_value' => $cf_value,
                                                                          )      );

                $this->ipsclass->DB->query("INSERT INTO ibf_registry_field_entries (" .$db_string['FIELD_NAMES']. ") VALUES (". $db_string['FIELD_VALUES'] .")");
            }
        }

        unset($db_string);

        // Do we need a line break?
        $error_text = $this->lib['upload']->error_msg();

        if ( empty($error_text) == FALSE )
        {
        	'<br />'. $error_text;
        }

        // Present message
        $this->ipsclass->print->redirect_screen( $this->ipsclass->lang['modify_car_success']  . $error_text, "autocom=".REGISTRY_URL."&amp;cmd=manage_item&amp;CID={$this->ipsclass->input['CID']}" );
    }


    /**
     * Insertion of new item into Fusion Registry
     *
     * @return string Failure returns template 'message'
     */
    function do_new()
    {
        // Do they have permission?
        if ( ($this->ipsclass->check_perms($this->registry_config['add_perms']) != TRUE) or !($this->ipsclass->member['id']) )
        {
            $this->ipsclass->Error( array( LEVEL => 1, MSG => 'no_permission') );
        }

        // Make sure they haven't exceeded the max vehicle limit
        $this->ipsclass->DB->query("SELECT count(*) AS total_cars FROM ibf_registry_items WHERE member_id = '". $this->ipsclass->member['id'] ."'");
        $row = $this->ipsclass->DB->fetch_row();

        if ($row['total_cars'] >= $this->registry_config['max_user_cars'])
        {
            // Sorry, too many vehicles :)
            $data = array( message    => $this->ipsclass->lang['exceeded_car_limit'],
                           next       => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=idx",
                           next_title => $this->ipsclass->lang['main_menu'],
                         );

            // Return the message
            return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
        }

        // Let's make sure we have all the required fields, grab all
        //  the defs first, then filter out all the ones required.
        $cf_defs = $this->lib['custom_fields']->get_cf_defs();

        $cf_required = array();

        foreach ( $cf_defs as $cf_id => $cf_row )
        {
            if ( $cf_row['field_required'] == 1 )
            {
                $cf_required[$cf_id] = $cf_row;
            }
        }

        // Compile list of missing fields (if any)
        $missing_fields = '';

        foreach ( $cf_required as $cf_id => $cf_row )
        {
            // We have to special case the make/model since they don't use the field_id as the field name
            if ( $cf_row['field_options'] == 'make' or $cf_row['field_options'] == 'model' )
            {
                if ( !isset($this->ipsclass->input[$cf_row['field_options']]) or empty($this->ipsclass->input[$cf_row['field_options']]) )
                {
                    $missing_fields .= $cf_row['field_name'] . ', ';
                }
            }
            else
            {
                if ( !isset($this->ipsclass->input[$cf_id]) or empty($this->ipsclass->input[$cf_id]) )
                {
                    $missing_fields .= $cf_row['field_name'] . ', ';
                }
            }
        }

        // If we found any report to user and bomb out
        if ( $missing_fields )
        {
            $missing_fields = substr($missing_fields, 0, -2);

            $error = preg_replace( "/<#MISSING_FIELDS#>/", $missing_fields, $this->ipsclass->lang['required_field_missing'] );

            // Sorry bud, we need/require this info!
            $data = array(
                            message    => $error,
                            next       => "javascript:history.go(-1)",
                            next_title => $this->ipsclass->lang['go_back'],
                         );

            // Return the message
            return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
        }

        // Process the custom fields input
        $cf_input = $this->lib['custom_fields']->process_cf_input($cf_defs);

        // Will be used to store the created and updated time in DB.
        // We are not using mysql's timestamp format because we are
        // control freaks :)
        $epoch_time = time();

        // This constructs the FIELD_NAMES and FIELD_VALUES for sql
        $db_string = $this->ipsclass->DB->compile_db_insert_string( array( 'member_id'           => $this->ipsclass->member['id'],
                                                                           'date_created'        => $epoch_time,
                                                                           'date_updated'        => $epoch_time,
                                                                           'guestbook_pm_notify' => $this->ipsclass->input['guestbook_pm_notify'],
                                                                  )      );

        // Execute the sql call
        $this->ipsclass->DB->query("INSERT INTO ibf_registry_items (" .$db_string['FIELD_NAMES']. ") VALUES (". $db_string['FIELD_VALUES'] .")");

        unset($db_string);

        // Save the vehicle id for later use
        $cid = $this->ipsclass->DB->get_insert_id();

        // Now save their custom field data
        foreach ( $cf_input as $cf_id => $cf_value )
        {
            $db_string = $this->ipsclass->DB->compile_db_insert_string( array( 'field_id' => $cf_id,
                                                                               'item_id' => $cid,
                                                                               'field_value' => $cf_value,
                                                                      )      );

            $this->ipsclass->DB->query("INSERT INTO ibf_registry_field_entries (" .$db_string['FIELD_NAMES']. ") VALUES (". $db_string['FIELD_VALUES'] .")");
        }

        unset($db_string);

        // Grab that image, if they have permission!
        if ( $this->ipsclass->check_perms($this->registry_config['upload_perms']) == TRUE )
        {
            $sql_image_id = $this->lib['upload']->process_upload('registry_gallery',$cid);
        }

        // Record the uploaded image (if any)
        if ( is_int($sql_image_id) && ($this->lib['upload']->error_msg() == "") )
        {
            // Insert out gallery entry
            $db_string = $this->ipsclass->DB->compile_db_insert_string( array( 'item_id' => $cid,
                                                                               'image_id' => $sql_image_id,
                                                                      )      );

            $this->ipsclass->DB->query("INSERT INTO ibf_registry_gallery (". $db_string['FIELD_NAMES']. ") VALUES (". $db_string['FIELD_VALUES'] .")");

            // Make sure it was an image they uploaded
            $this->ipsclass->DB->query("SELECT attach_is_image FROM ibf_registry_images WHERE attach_id='".$sql_image_id."'");

            $image_check = $this->ipsclass->DB->fetch_row();

            if ($image_check['attach_is_image'])
            {
                // Update the vehicle entry for this highlight image
                $db_string = $this->ipsclass->DB->compile_db_update_string( array( 'image_id' => $sql_image_id ) );

                $this->ipsclass->DB->query("UPDATE ibf_registry_items SET $db_string WHERE id = '$cid'");
            }
        }

        // Do we need a line break?
        $error_text = $this->lib['upload']->error_msg();

        if ( empty($error_text) == FALSE )
        {
        	$error_text = '<br />'. $error_text;
        }

        // Present message
        $this->ipsclass->print->redirect_screen( $this->ipsclass->lang['new_car_success'] . $error_text, "autocom=".REGISTRY_URL."&amp;cmd=manage_item&amp;CID=$cid" );
    }


    /**
     * Record the end user's submitted ratings
     */
    function do_rating()
    {
        // Do they have permission?
        if ( ( $this->ipsclass->check_perms($this->registry_config['interact_perms']) != TRUE ) OR
             ($this->registry_config['enable_item_ratings'] != 1) )
        {
            $this->ipsclass->Error( array( LEVEL => 1, MSG => 'no_permission') );
        }

        // Check for valid item_id
        $this->ipsclass->DB->query("SELECT id FROM ibf_registry_items WHERE id = '". $this->ipsclass->input['item_id'] ."'");
        if ( !$this->ipsclass->DB->get_num_rows() )
        {
            $this->ipsclass->Error( array( LEVEL => 1, MSG => 'is_broken_link') );
        }

        // Flood check
        $this->ipsclass->DB->query("SELECT MAX(rating_date) as last_rating FROM ibf_registry_rating_entries WHERE member_id = '". $this->ipsclass->member['id'] ."'");
        $row = $this->ipsclass->DB->fetch_row();

        if ( $this->ipsclass->vars['flood_control'] > 0 )
        {
            if ($this->ipsclass->member['g_avoid_flood'] != 1)
            {
                if ( time() - $row['last_rating'] < $this->ipsclass->vars['flood_control'] )
                {
                    $this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'flood_control' , 'EXTRA' => $this->ipsclass->vars['flood_control'] ) );
                }
            }
        }

        // Compile list of their ratings against valid ratings
        $user_ratings = array();

        $ratings_def = $this->lib['ratings']->get_rating_defs();

        foreach ( $ratings_def as $rating_id => $rating_row )
        {
            if ( !empty( $this->ipsclass->input[$rating_id] ) )
            {
                $user_ratings[$rating_id] = intval( $this->ipsclass->input[$rating_id] );
            }
        }

        // Rate it!
        $this->lib['ratings']->record_rating( $this->ipsclass->input['item_id'], $user_ratings );

        // Present message
        $this->ipsclass->print->redirect_screen( $this->ipsclass->lang['rating_success'], "autocom=".REGISTRY_URL."&amp;cmd=view_item&amp;CID={$this->ipsclass->input['item_id']}" );
    }


    /**
     * Build the HTML for the main modify menu screen
     *
     * @return string Success returns template 'modify_menu'; Failure returns template 'message'
     */
    function manage_menu()
    {
        // For security measures we are going to make sure that the person
        // logged in is the owner of the item trying to be modified.  So first
        // we need to select the item and find out who owns it ;)
        $this->ipsclass->DB->query( "SELECT g.id, g.image_id, g.member_id, g.views, g.date_updated, g.date_created,
                                        m.members_display_name, ( SUM(mods.price) + SUM(mods.install_price) ) AS total_spent,
                                        count(mods.id) AS total_mods, me.avatar_location, me.avatar_size,
                                        images.attach_hits, images.attach_ext, images.attach_id,
                                        images.attach_file, images.attach_thumb_location, images.attach_location
                                     FROM ( ibf_members AS m, ibf_registry_items AS g )
                                        LEFT JOIN ibf_registry_images AS images ON images.attach_id = g.image_id
                                        LEFT JOIN ibf_registry_mods AS mods ON g.id = mods.item_id
                                        LEFT JOIN ibf_member_extra AS me ON m.id = me.id
                                     WHERE g.id = '". $this->ipsclass->input['CID'] ."' AND m.id = g.member_id
                                     GROUP BY g.id");

        $vehicle_data = $this->ipsclass->DB->fetch_row();

        // Now let's do the check
        if ( $this->ipsclass->member['id'] != $vehicle_data['member_id'] )
        {
            if ( $this->ipsclass->member['g_is_supmod'] != 1 )
            {
                // Get them outta here, they don't own this item!!!
                $data = array(
                                message    => $this->ipsclass->lang['not_owner_failure'],
                                next       => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=idx",
                                next_title => $this->ipsclass->lang['main_menu'],
                             );

                // Return the message
                return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
            }
        }

        // Change times to human readable format
        $vehicle_data['date_updated'] = $this->ipsclass->get_date( $vehicle_data['date_updated'], 'LONG' );
        $vehicle_data['date_created'] = $this->ipsclass->get_date( $vehicle_data['date_created'], 'LONG' );

        // Parse the comments 'safely'
        $vehicle_data['comments'] = $this->lib['parser']->pre_display_parse( $vehicle_data['comments'] );

        // Do we have a highlight image?  If so, prep the HTML
        if (empty($vehicle_data['image_id']) == FALSE)
        {
            // Do we have a thumbnail?  If so, our job is simple here :)
            if ( (empty($vehicle_data['attach_thumb_location']) == FALSE) and
                 ($vehicle_data['attach_thumb_location'] != $vehicle_data['attach_location']) and
                 (@file_exists($this->ipsclass->vars['upload_dir']."/".$vehicle_data['attach_thumb_location'])) )
            {
                // Form the correct image link if it's remote
                $image_link = "{$this->ipsclass->vars['upload_url']}/{$vehicle_data['attach_thumb_location']}";

                // Yippie, our thumbnail is already made for us :)
                $vehicle_data['highlight_image'] = $this->ipsclass->compiled_templates['skin_registry_core']->show_real_img_thumb(
                                                        array(  'filename' => $image_link,
                                                                 'hits'     => $vehicle_data['attach_hits'],
                                                                 'type'     => 'registry',
                                                                 'id'       => $vehicle_data['id'],
                                                      )      );
            }
            else
            {
                // Since we don't have a pre-made thumb we are going
                //   to fall back on the old style :(

                $img_size = array();

                // Is this a remote image?
                if ( ($vehicle_data['attach_thumb_location'] == "remote" ) OR preg_match("/^http:\/\//i", $vehicle_data['attach_location']) )
                {
                    $img_size = @GetImageSize( $vehicle_data['attach_location'] );
                }
                else
                {
                    $img_size = @GetImageSize( $this->ipsclass->vars['upload_url']."/".$vehicle_data['attach_location'] );
                }

                // Form the correct image link if it's remote
                $image_link = ( ($vehicle_data['attach_thumb_location'] == "remote") OR preg_match("/^http:\/\//i", $vehicle_data['attach_location']) )
                            ? $vehicle_data['attach_location']
                            : "{$this->ipsclass->vars['upload_url']}/{$vehicle_data['attach_location']}";

                if ( $img_size[0] < 1 )
                {
                    $img_size    = array();
                    $img_size[0] = $this->registry_config['thumbnail_resolution'] + 1;
                    $img_size[1] = $this->registry_config['thumbnail_resolution'] + 1;
                }

                //----------------------------------------------------
                // Do we need to scale?
                //----------------------------------------------------

                if ( ( $img_size[0] <= $this->registry_config['thumbnail_resolution'] ) AND
                     ( $img_size[1] <= $this->registry_config['thumbnail_resolution'] ) )
                {
                    $vehicle_data['highlight_image'] = $this->ipsclass->compiled_templates['skin_registry_core']->show_img( $image_link );
                }
                else
                {
                    $im = $this->ipsclass->scale_image(
                            array( 'max_width'  => $this->registry_config['thumbnail_resolution'],
                                   'max_height' => $this->registry_config['thumbnail_resolution'],
                                   'cur_width'  => $img_size[0],
                                   'cur_height' => $img_size[1]
                          )      );


                    $vehicle_data['highlight_image'] = $this->ipsclass->compiled_templates['skin_registry_core']->show_img_thumb(
                                                            array( 'filename' => $image_link,
                                                                   'width'    => $im['img_width'],
                                                                   'height'   => $im['img_height'],
                                                                   'hits'     => $vehicle_data['attach_hits'],
                                                                   'type'     => 'registry',
                                                                   'id'       => $vehicle_data['id'],
                                                          )      );
                }
            }
        }

        // Now we need to grab all their mods

        // We are going to start off by getting the list of distinct
        //   categories of mods that this vehicle has, then we will grab
        //   each mod for the category.
        $cat_query_id = $this->ipsclass->DB->query("SELECT DISTINCT (mods.category_id),cats.title,cats.image_id
                                                    FROM ( ibf_registry_mods AS mods, ibf_registry_categories AS cats )
                                                    WHERE mods.item_id = '". $this->ipsclass->input['CID'] ."' AND cats.id = mods.category_id
                                                    GROUP BY cats.title ASC");

        $mods_html = '';

        while ( $cat_row = $this->ipsclass->DB->fetch_row($cat_query_id) )
        {
            // Grab the mods for this category for this item
            $mod_query_id = $this->ipsclass->DB->query("SELECT mods.*, images.attach_id, images.attach_hits, images.attach_ext,
                                                            images.attach_file, images.attach_thumb_location
                                                        FROM ( ibf_registry_mods AS mods, ibf_registry_items AS g )
                                                            LEFT JOIN ibf_registry_images AS images ON images.attach_id = mods.image_id
                                                        WHERE mods.item_id = '". $this->ipsclass->input['CID'] ."'
                                                          AND mods.category_id = '". $cat_row['category_id'] ."'
                                                          AND g.id = '". $this->ipsclass->input['CID'] ."'
                                                        ORDER BY title ASC");

            $mod_list = '';
            while ( $mod_row = $this->ipsclass->DB->fetch_row($mod_query_id) )
            {
                // Convert the dates into human readable format
                $mod_row['date_updated'] = $this->ipsclass->get_date( $mod_row['date_updated'], 'LONG' );
                $mod_row['date_created'] = $this->ipsclass->get_date( $mod_row['date_created'], 'LONG' );

                // If we have an attached image, give it an icon
                if (!empty($mod_row['image_id']))
                {
                    $mod_row['icon'] = '<img src="'. $this->ipsclass->vars['img_url'] .'/registry_images/picture.png" border="0" alt="Picture" title="Picture" />';
                }

                $mod_list .= $this->ipsclass->compiled_templates['skin_registry_item']->modify_mod_category_row($mod_row);
            }

            // Now let's build the category table
            $cat_row['mod_list'] = $mod_list;
            $mods_html .= $this->ipsclass->compiled_templates['skin_registry_item']->modify_mod_category($cat_row);
        }

        // Prepare the mods HTML for the big picture
        $vehicle_data['mods'] = $mods_html;

        // Go get all our custom fields data
        $cf_data = $this->lib['custom_fields']->process_cf( array( 'type' => 'view', 'CID' => $vehicle_data['id'] ) );

        $vehicle_data['custom_fields'] = $cf_data['html'];

        // Setup our highlight for the title
        $cf_highlight = $this->lib['custom_fields']->get_cf_highlight();

        $vehicle_data['highlight_field_value'] = '';

        foreach ( $cf_highlight as $cf_field_id => $cf_highlight_row )
        {
            $vehicle_data['highlight_field_value'] .= $this->lib['custom_fields']->process_cf_value( array( 'def' => $cf_highlight_row,
                                                                                                            'value' => $cf_data['cf_entries'][$cf_field_id]['field_value'],
                                                                                                            'type' => 'view',
                                                                                                   )      );
            // Append space for readability
            $vehicle_data['highlight_field_value'] .= ' ';
        }

        // Get our fancy popup javascript
        $vehicle_data['popup_javascript'] = $this->ipsclass->compiled_templates['skin_registry_core']->popup_javascript();

        // Set page title
        $this->page_title = $this->ipsclass->lang['manage_vehicle'];

        // Add to our Nav Bar
        $this->nav_bar[] = "<a href='{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=manage_item&amp;CID={$this->ipsclass->input['CID']}'>{$vehicle_data['highlight_field_value']}</a>";

        return $this->ipsclass->compiled_templates['skin_registry_item']->manage_menu($vehicle_data);
    }


    /**
     * Build the HTML menu for modifying an item
     *
     * @return string Success returns template 'modify_menu'; Failure returns template 'message'
     */
    function modify_menu()
    {
        // For security measures we are going to make sure that the person
        //   logged in is the owner of the item trying to be modified.  So first
        //   we need to select the item and find out who owns it ;)
        // To conserve SQL calls we are piggy-backing the image lookup here.
        $this->ipsclass->DB->query( "SELECT g.id, g.image_id, g.member_id, g.views, g.date_updated,
                                        g.date_created, images.attach_id, images.attach_hits, images.attach_ext,
                                        images.attach_file, images.attach_thumb_location, images.attach_location,
                                        g.guestbook_pm_notify
                                     FROM ibf_registry_items AS g
                                        LEFT JOIN ibf_registry_images AS images ON images.attach_id = g.image_id
                                     WHERE g.id = '" . $this->ipsclass->input['CID'] . "'");

        $vehicle_data = $this->ipsclass->DB->fetch_row();

        // Now let's do the check
        if ( $this->ipsclass->member['id'] != $vehicle_data['member_id'] )
        {
            if ( $this->ipsclass->member['g_is_supmod'] != 1 )
            {
                // Get them outta here, they don't own this item!!!
                $data = array(
                                message    => $this->ipsclass->lang['not_owner_failure'],
                                next       => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=idx",
                                next_title => $this->ipsclass->lang['main_menu'],
                             );

                // Return the message
                return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
            }
        }

        // Go get all our custom fields data
        $cf_data = $this->lib['custom_fields']->process_cf( array( 'CID' => $this->ipsclass->input['CID'], 'type' => 'form' ) );

        $cf_special_fields = $this->lib['custom_fields']->process_cf_special_defs( array( 'cf_defs' => $cf_data['cf_defs'] ) );

        // Only add the javscript to the output if they are using the make/model special fields
        if ( in_array( 'make', array_keys($cf_special_fields) ) and in_array( 'model', array_keys($cf_special_fields) ) )
        {
            $vehicle_data['vehicle_javascript'] = $this->ipsclass->compiled_templates['skin_registry_item']->vehicle_javascript( $this->lib['functions']->build_vehicle_javascript() );

            $make_value = $this->lib['custom_fields']->process_cf_value( array( 'def' => $cf_special_fields['make'] ,
                                                                                'value' => $cf_data['cf_entries'][ $cf_special_fields['make']['field_id'] ]['field_value'],
                                                                                'type' => 'form' ) );

            $model_value = $this->lib['custom_fields']->process_cf_value( array( 'def' => $cf_special_fields['model'] ,
                                                                                 'value' => $cf_data['cf_entries'][ $cf_special_fields['model']['field_id'] ]['field_value'],
                                                                                 'type' => 'form' ) );

            $vehicle_data['invoke_vehicle_javascript'] = $this->ipsclass->compiled_templates['skin_registry_item']->invoke_vehicle_javascript(
                                                            array( 'form' => 'MODIFY',
                                                                   'make' => $make_value,
                                                                   'model' => $model_value
                                                          )      );
        }

        $vehicle_data['custom_fields'] = $cf_data['html'];

        // Set page title
        $this->page_title = $this->ipsclass->lang['modify_car'];

        // Setup our highlight for the title
        $cf_highlight = $this->lib['custom_fields']->get_cf_highlight();

        $vehicle_data['highlight_field_value'] = '';

        foreach ( $cf_highlight as $cf_field_id => $cf_highlight_row )
        {
            $vehicle_data['highlight_field_value'] .= $this->lib['custom_fields']->process_cf_value( array( 'def' => $cf_highlight_row,
                                                                                                            'value' => $cf_data['cf_entries'][$cf_field_id]['field_value'],
                                                                                                            'type' => 'form',
                                                                                                   )      );
            // Append space for readability
            $vehicle_data['highlight_field_value'] .= ' ';
        }

        // Add to our Nav Bar
        $this->nav_bar[] = "<a href='{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=manage_item&amp;CID={$this->ipsclass->input['CID']}'>". $vehicle_data['highlight_field_value'] ."</a>";

        // PM notify checked or not?
        $vehicle_data['guestbook_pm_notify'] = ($vehicle_data['guestbook_pm_notify'] == 1)
                                             ? 'checked'
                                             : '';

        // Wrap it up by returning data
        return $this->ipsclass->compiled_templates['skin_registry_item']->modify_menu($vehicle_data);
    }


    /**
     * Build the HTML menu for creating a new item
     *
     * @return string Success returns template 'add_new_vehicle_menu'; Failure returns template 'message'
     */
    function new_menu()
    {
        // Do they have permission?
        if ( ($this->ipsclass->check_perms($this->registry_config['add_perms']) != TRUE) or !($this->ipsclass->member['id']) )
        {
            $this->ipsclass->Error( array( LEVEL => 1, MSG => 'no_permission') );
        }

        // Make sure they haven't exceeded the max vehicle limit
        $this->ipsclass->DB->query("SELECT count(*) AS total_cars FROM ibf_registry_items WHERE member_id = '". $this->ipsclass->member['id'] ."'");
        $row = $this->ipsclass->DB->fetch_row();

        if ($row['total_cars'] >= $this->registry_config['max_user_cars'])
        {
            // Sorry, too many vehicles :)
            $data = array( message    => $this->ipsclass->lang['exceeded_car_limit'],
                           next       => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=idx",
                           next_title => $this->ipsclass->lang['main_menu'],
                         );

            // Return the message
            return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
        }

        // If they are allowed to upload images, let's prepare the HTML
        if ( ($this->registry_config['allow_image_upload'] == 1) and
             ($this->registry_config['max_image_kbytes'] > 0) and
             ($this->ipsclass->check_perms($this->registry_config['upload_perms']) == TRUE) )
        {
            $size_string = $this->ipsclass->size_format( $this->registry_config['max_image_kbytes'] * 1024 );

            $data['upload'] = $this->ipsclass->compiled_templates['skin_registry_core']->upload_field( $size_string, $this->registry_config['max_image_resolution'] );

            // If they are allowed to use url images, prep the HTML
            if ( $this->registry_config['allow_image_url'] == 1 )
            {
                $data['upload_url'] = $this->ipsclass->compiled_templates['skin_registry_core']->upload_url_field( array( url => 'http://',
                                                                                                                          target_form => 'new_vehicle'
                                                                                                                 )      );
            }
        }

        // Go get all our custom fields data
        $cf_data = $this->lib['custom_fields']->process_cf( array( 'type' => 'form' ) );

        $cf_special_fields = $this->lib['custom_fields']->process_cf_special_defs( array( 'cf_defs' => $cf_data['cf_defs'] ) );

        // Only add the javscript to the output if they are using the make/model special fields
        if ( in_array( 'make', array_keys($cf_special_fields) ) and in_array( 'model', array_keys($cf_special_fields) ) )
        {
            $data['vehicle_javascript'] = $this->ipsclass->compiled_templates['skin_registry_item']->vehicle_javascript( $this->lib['functions']->build_vehicle_javascript() );

            $data['invoke_vehicle_javascript'] = $this->ipsclass->compiled_templates['skin_registry_item']->invoke_vehicle_javascript( array( 'form' => 'new_vehicle' ) );
        }

        $data['custom_fields'] = $cf_data['html'];

        // Set page title
        $this->page_title = $this->ipsclass->lang['new_car'];

        // Add to our Nav Bar
        $this->nav_bar[] = $this->ipsclass->lang['new_car'];

        return $this->ipsclass->compiled_templates['skin_registry_item']->add_new_menu($data);
    }


    /**
     * Shows end user the submit ratings form for an item
     *
     * @todo Load previous ratings into form
     * @todo Grab highlight custom field data to display on top for description
     */
    function rating_menu()
    {
        // Do they have permission?
        if ( ($this->ipsclass->check_perms($this->registry_config['interact_perms']) != TRUE) OR $this->registry_config['enable_item_ratings'] != 1 OR
              !($this->ipsclass->member['id']) )
        {
            $this->ipsclass->Error( array( LEVEL => 1, MSG => 'no_permission') );
        }

        // Do we have a valid target to rate?
        $rs = $this->ipsclass->DB->query("SELECT id FROM ibf_registry_items WHERE id = '". $this->ipsclass->input['item_id'] ."'");

        // If they sent in invalid data, bounce them out
        if ( !$this->ipsclass->DB->get_num_rows() )
        {
            $this->ipsclass->Error( array( LEVEL => 1, MSG => 'is_broken_link') );
        }

        // Load the ratings defs
        $rating_defs = $this->lib['ratings']->get_rating_defs( array( 'ORDER BY' => 'rating_order ASC' ) );

        // They shouldn't even get to this function if there aren't rating defs
        if ( empty($rating_defs) )
        {
            $this->ipsclass->Error( array( LEVEL => 1, MSG => 'is_broken_link') );
        }

        // Loop through and produce our inner html
        $inner_html = '';

        foreach ( $rating_defs as $rating_id => $rating_row )
        {
            // Create our html select field
            $select_html = $this->lib['ratings']->build_rating_select( array( 'rating_row' => $rating_row ) );

            // Create this rating row
            $inner_html .= $this->ipsclass->compiled_templates['skin_registry_item']->rating_row_input( array( 'rating_name' => $rating_row['rating_name'],
                                                                                                               'rating_select' => $select_html,
                                                                                                      )      );
        }

        $rating_desc = preg_replace( "/<#RATING_MIN#>/", $this->registry_config['rating_min'], $this->ipsclass->lang['submit_ratings_desc'] );
        $rating_desc = preg_replace( "/<#RATING_MAX#>/", $this->registry_config['rating_max'], $rating_desc );

        return $this->ipsclass->compiled_templates['skin_registry_item']->rating_menu( array( 'item_id' => $this->ipsclass->input['item_id'],
                                                                                              'rating_inputs' => $inner_html,
                                                                                              'rating_desc' => $rating_desc,
                                                                                     )      );
    }


    /**
     * View an item
     *
     * This function is the most intensive function in the Fusion Registry. It
     * has to pull together every detail, for all the details of an item.
     *
     * @return string Template 'view'
     */
    function view()
    {
        // Do they have permission to browse?
        if ( $this->ipsclass->check_perms($this->registry_config['browse_perms']) != TRUE )
        {
            $this->ipsclass->Error( array( LEVEL => 1, MSG => 'no_permission') );
        }

        // Got attachment types?
        if ( !is_array( $this->ipsclass->cache['attachtypes'] ) )
        {
            $this->ipsclass->cache['attachtypes'] = array();

            $this->ipsclass->DB->simple_construct( array( 'select' => 'atype_extension,atype_mimetype,atype_post,atype_photo,atype_img', 'from' => 'attachments_type', 'where' => "atype_photo=1 OR atype_post=1" ) );
            $this->ipsclass->DB->simple_exec();

            while ( $r = $this->ipsclass->DB->fetch_row() )
            {
                $this->ipsclass->cache['attachtypes'][ $r['atype_extension'] ] = $r;
            }
        }

        // Grab the vehicle & member data, calculate the total spent while we're at it
        $this->ipsclass->DB->query("SELECT g.id, g.image_id, g.member_id, g.views, g.date_updated, g.date_created,
                                        m.members_display_name, ( SUM(mods.price) + SUM(mods.install_price) ) AS total_spent,
                                        count(mods.id) AS total_mods, me.avatar_location, me.avatar_size, images.attach_id,
                                        images.attach_hits, images.attach_file, images.attach_thumb_location,
                                        images.attach_is_image, images.attach_location, me.avatar_type
                                    FROM ( ibf_members AS m, ibf_registry_items AS g )
                                        LEFT JOIN ibf_registry_images AS images ON images.attach_id = g.image_id
                                        LEFT JOIN ibf_registry_mods AS mods ON g.id = mods.item_id
                                        LEFT JOIN ibf_member_extra AS me ON m.id = me.id
                                    WHERE g.id = '". $this->ipsclass->input['CID'] ."' AND m.id = g.member_id
                                    GROUP BY g.id");

        $vehicle_data = $this->ipsclass->DB->fetch_row();

        // If they sent in invalid data, bounce them out
        if ( !$this->ipsclass->DB->get_num_rows() )
        {
            $this->ipsclass->Error( array( LEVEL => 1, MSG => 'is_broken_link') );
        }

        // If total spent is zero, make sure 0 is displayed
        $vehicle_data['total_spent'] = $vehicle_data['total_spent'] ? $vehicle_data['total_spent'] : 0;

        // Pretty avatar
        $vehicle_data['avatar'] = $this->ipsclass->get_avatar( $vehicle_data['avatar_location'],
                                                               $this->ipsclass->member['view_avs'],
                                                               $vehicle_data['avatar_size'],
                                                               $vehicle_data['avatar_type']
                                                             );

        // Change times to human readable format
        $vehicle_data['date_updated'] = $this->ipsclass->get_date( $vehicle_data['date_updated'], 'LONG' );
        $vehicle_data['date_created'] = $this->ipsclass->get_date( $vehicle_data['date_created'], 'LONG' );

        // Do we have a highlight image?  If so, prep the HTML
        if ( (empty($vehicle_data['image_id']) == FALSE) AND $vehicle_data['attach_is_image'] )
        {
            // Do we have a thumbnail?  If so, our job is simple here :)
            if ( (empty($vehicle_data['attach_thumb_location']) == FALSE) and
                 ($vehicle_data['attach_thumb_location'] != $vehicle_data['attach_location']) and
                 (@file_exists($this->ipsclass->vars['upload_dir']."/".$vehicle_data['attach_thumb_location'])) )
            {
                // Form the correct image link if it's remote
                $image_link = "{$this->ipsclass->vars['upload_url']}/{$vehicle_data['attach_thumb_location']}";

                // Yippie, our thumbnail is already made for us :)
                $vehicle_data['highlight_image'] = $this->ipsclass->compiled_templates['skin_registry_core']->show_real_img_thumb(
                                                        array( 'filename' => $image_link,
                                                               'title'    => $vehicle_data['attach_file'],
                                                               'hits'     => $vehicle_data['attach_hits'],
                                                               'type'     => 'registry',
                                                               'id'       => $vehicle_data['id'],
                                                       )      );
            }
            else
            {
                // Since we don't have a pre-made thumb we are going
                //   to fall back on the old style :(

                $img_size = array();

                // Is this a remote image?
                if ( ($vehicle_data['attach_thumb_location'] == "remote") OR preg_match("/^http:\/\//i", $vehicle_data['attach_location']) )
                {
                    $img_size = @GetImageSize( $vehicle_data['attach_location'] );
                }
                else
                {
                    $img_size = @GetImageSize( $this->ipsclass->vars['upload_url']."/".$vehicle_data['attach_location'] );
                }

                if ( $img_size[0] < 1 )
                {
                    $img_size    = array();
                    $img_size[0] = $this->registry_config['thumbnail_resolution'] + 1;
                    $img_size[1] = $this->registry_config['thumbnail_resolution'] + 1;
                }

                // Form the correct image link if it's remote
                $image_link = ( ($vehicle_data['attach_thumb_location'] == "remote") OR preg_match("/^http:\/\//i", $vehicle_data['attach_location']) )
                            ? $vehicle_data['attach_location']
                            : "{$this->ipsclass->vars['upload_url']}/{$vehicle_data['attach_location']}";

                //----------------------------------------------------
                // Do we need to scale?
                //----------------------------------------------------

                if ( ( $img_size[0] <= $this->registry_config['thumbnail_resolution'] ) AND
                     ( $img_size[1] <= $this->registry_config['thumbnail_resolution'] ) )
                {
                    $vehicle_data['highlight_image'] = $this->ipsclass->compiled_templates['skin_registry_core']->show_real_img_thumb(
                                                            array( 'filename' => $image_link,
                                                                   'title'    => $vehicle_data['attach_file'],
                                                                   'hits'     => $vehicle_data['attach_hits'],
                                                                   'type'     => 'registry',
                                                                   'id'       => $vehicle_data['id'],
                                                           )      );
                }
                else
                {
                    $im = $this->ipsclass->scale_image( array( 'max_width'  => $this->registry_config['thumbnail_resolution'],
                                                    'max_height' => $this->registry_config['thumbnail_resolution'],
                                                    'cur_width'  => $img_size[0],
                                                    'cur_height' => $img_size[1]
                                           )      );

                    $vehicle_data['highlight_image'] = $this->ipsclass->compiled_templates['skin_registry_core']->show_img_thumb(
                                                            array( 'filename' => $image_link,
                                                                   'title'    => $vehicle_data['attach_file'],
                                                                   'width'    => $im['img_width'],
                                                                   'height'   => $im['img_height'],
                                                                   'hits'     => $vehicle_data['attach_hits'],
                                                                   'type'     => 'registry',
                                                                   'id'       => $vehicle_data['id'],
                                                          )      );
                }
            }
        }

        // Now let's check for vehicle gallery images
        // Let's start creating the vehicle images part of the gallery now
        $gallery_vehicle_images = $this->ipsclass->compiled_templates['skin_registry_gallery']->gallery_item_header();

        $vehicle_images_found = FALSE;

        $gallery_query_id = $this->ipsclass->DB->query( "SELECT gallery.id, images.attach_id, images.attach_hits, images.attach_ext,
                                                            images.attach_file, images.attach_thumb_location, images.attach_is_image,
                                                            images.attach_location
                                                         FROM ibf_registry_images AS images
                                                            LEFT JOIN ibf_registry_gallery AS gallery ON images.attach_id = gallery.image_id
                                                            LEFT JOIN ibf_registry_items AS garage ON gallery.item_id = garage.id
                                                         WHERE garage.id = '" . $this->ipsclass->input['CID'] . "'" );

        // A quick flag set if we do indeed have vehicle gallery images
        if ( $this->ipsclass->DB->get_num_rows() > 0 )
        {
            $vehicle_images_found = TRUE;
        }

        while ( $gallery_data = $this->ipsclass->DB->fetch_row($gallery_query_id) )
        {
            if ( $gallery_data['attach_is_image'] )
            {
                // Do we have a thumbnail?  If so, our job is simple here :)
                if ( (empty($gallery_data['attach_thumb_location']) == FALSE) AND
                     (@file_exists($this->ipsclass->vars['upload_dir']."/".$gallery_data['attach_thumb_location'])) AND
                     ($gallery_data['attach_thumb_location'] != "remote") AND
                     ($gallery_data['attach_thumb_location'] != $gallery_data['attach_location']) )
                {
                    // Form the image link
                    $image_link = "{$this->ipsclass->vars['upload_url']}/{$gallery_data['attach_thumb_location']}";

                    // Yippie, our thumbnail is already made for us :)
                    $gallery_vehicle_images .= $this->ipsclass->compiled_templates['skin_registry_gallery']->gallery_item_thumb(
                                                    array( 'filename' => $image_link,
                                                           'title'    => $gallery_data['attach_file'],
                                                           'hits'     => $gallery_data['attach_hits'],
                                                           'type'     => 'registry_gallery',
                                                           'id'       => $gallery_data['id'],
                                                  )      );
                }
                else
                {
                    // Since we don't have a pre-made thumb we are going
                    //   to fall back on the old style :(
                    $img_size = array();

                    // Is this a remote image?
                    if ( ($gallery_data['attach_thumb_location'] == "remote") OR preg_match("/^http:\/\//i", $gallery_data['attach_location']) )
                    {
                        $img_size = @GetImageSize( $gallery_data['attach_location'] );
                    }
                    else
                    {
                        $img_size = @GetImageSize( $this->ipsclass->vars['upload_url']."/".$gallery_data['attach_location'] );
                    }

                    if ( $img_size[0] < 1 )
                    {
                        $img_size    = array();
                        $img_size[0] = $this->registry_config['thumbnail_resolution'] + 1;
                        $img_size[1] = $this->registry_config['thumbnail_resolution'] + 1;
                    }

                    // Form the correct image link if it's remote
                    $image_link = ( ($gallery_data['attach_thumb_location'] == "remote") OR preg_match("/^http:\/\//i", $gallery_data['attach_location']) )
                                ? $gallery_data['attach_location']
                                : "{$this->ipsclass->vars['upload_url']}/{$gallery_data['attach_location']}";

                    //----------------------------------------------------
                    // Do we need to scale?
                    //----------------------------------------------------

                    if ( ( $img_size[0] <= $this->registry_config['thumbnail_resolution'] ) AND
                         ( $img_size[1] <= $this->registry_config['thumbnail_resolution'] ) )
                    {
                        $gallery_vehicle_images .= $this->ipsclass->compiled_templates['skin_registry_gallery']->gallery_item_thumb(
                                                        array( 'filename' => $image_link,
                                                               'title'    => $gallery_data['attach_file'],
                                                               'hits'     => $gallery_data['attach_hits'],
                                                               'type'     => 'registry_gallery',
                                                               'id'       => $gallery_data['id'],
                                                     )      );
                    }
                    else
                    {
                        $im = $this->ipsclass->scale_image( array( 'max_width'  => $this->registry_config['thumbnail_resolution'],
                                                        'max_height' => $this->registry_config['thumbnail_resolution'],
                                                        'cur_width'  => $img_size[0],
                                                        'cur_height' => $img_size[1]
                                               )      );

                        $gallery_vehicle_images .= $this->ipsclass->compiled_templates['skin_registry_gallery']->gallery_item(
                                                        array( 'filename' => $image_link,
                                                                'title'    => $gallery_data['attach_file'],
                                                                'width'    => $im['img_width'],
                                                                'height'   => $im['img_height'],
                                                                'hits'     => $gallery_data['attach_hits'],
                                                                'type'     => 'registry_gallery',
                                                                'id'       => $gallery_data['id'],
                                                       )      );
                    } // End if scale
                } // End if thumbnail
            } // End if image
            else
            {
                // This appears to be a non-image attachment, let's show it!
                $gallery_vehicle_images .= $this->ipsclass->compiled_templates['skin_registry_core']->show_attachments(
                                                array( 'image' => $this->ipsclass->cache['attachtypes'][ $gallery_data['attach_ext'] ]['atype_img'],
                                                       'name'  => $gallery_data['attach_file'],
                                                       'id'    => $gallery_data['id'],
                                                       'type'  => 'registry_gallery',
                                              )       );
            }
        } // End while $gallery_data

        // Now let's finish off the vehicle pictures gallery if we have
        //   found any images.
        if ( $vehicle_images_found == TRUE )
        {
            // Append the footer
            $gallery_vehicle_images .= $this->ipsclass->compiled_templates['skin_registry_gallery']->gallery_section_footer();

            // Add this section to the gallery
            $gallery_sections['car_pictures'] = $gallery_vehicle_images;
        }
        else
        {
            // If we don't have any mod images, we aren't going
            //   to show this section.
            $gallery_sections['car_pictures'] = '';
        }

        // Update the views counter for this vehicle
        $this->ipsclass->DB->query("UPDATE ibf_registry_items SET views=views+1 WHERE id='". $this->ipsclass->input['CID'] ."'");

        // Since we are not directly outputing the modifications, but instead
        //   compiling them and then printing them out we can benefit by this
        //   process.  What we are going to do is while we are looping through
        //   the mods for the vehicle if we find an image we will add it to the
        //   gallery.  This will save us from having to do additional sql
        //   queries just for the vehicle gallery.

        $mod_images_found = 0;

        // We are going to start off by getting the list of distinct
        //   categories of mods that this vehicle has, then we will grab
        //   each mod for the category.
        $cat_query_id = $this->ipsclass->DB->query("SELECT DISTINCT (mods.category_id),cats.title
                                                    FROM ( ibf_registry_mods AS mods, ibf_registry_categories AS cats )
                                                    WHERE mods.item_id = '". $this->ipsclass->input['CID'] ."' AND cats.id = mods.category_id
                                                    GROUP BY cats.title ASC");

        $mods_html = '';
        while ( $cat_row = $this->ipsclass->DB->fetch_row($cat_query_id) )
        {
            // Grab the mods for this category for this vehicle
            $mod_query_id = $this->ipsclass->DB->query("SELECT m.*, images.attach_id, images.attach_hits, images.attach_ext,
                                                            images.attach_file, images.attach_thumb_location, images.attach_is_image,
                                                            images.attach_location
                                                        FROM ibf_registry_mods AS m
                                                          LEFT JOIN ibf_registry_images AS images ON images.attach_id = m.image_id
                                                        WHERE item_id = '". $this->ipsclass->input['CID'] ."'
                                                          AND category_id = '". $cat_row['category_id'] ."'
                                                        ORDER BY title ASC");

            $mod_list = '';
            while ( $mod_row = $this->ipsclass->DB->fetch_row($mod_query_id) )
            {
                // Convert the dates into human readable format
                $mod_row['date_updated'] = $this->ipsclass->get_date( $mod_row['date_updated'], 'LONG' );
                $mod_row['date_created'] = $this->ipsclass->get_date( $mod_row['date_created'], 'LONG' );

                // Plop the currency value in the mod data
                $mod_row['currency'] = $vehicle_data['currency'];

                // If we have an attached image, give it an icon
                if (!empty($mod_row['image_id']))
                {
                    $mod_row['icon'] = '<img src="'. $this->ipsclass->vars['img_url'] .'/registry_images/picture.png" border="0" alt="Picture" title="Picture" />';

                    // BEGIN mod gallery, if it's enabled!
                    if ($this->registry_config['show_mod_gallery'] == 1)
                    {
                        // Increment count
                        $mod_images_found++;

                        // If we have a set limit, make sure we haven't hit it
                        if ( ($this->registry_config['limit_mod_gallery'] AND ($this->registry_config['limit_mod_gallery_amount'] >= $mod_images_found))
                             OR !$this->registry_config['limit_mod_gallery'])
                        {
                            if ( $mod_row['attach_is_image'] )
                            {
                                // Do we have a thumbnail?  If so, our job is simple here :)
                                if ( (empty($mod_row['attach_thumb_location']) == FALSE) AND
                                     (@file_exists($this->ipsclass->vars['upload_dir']."/".$mod_row['attach_thumb_location'])) AND
                                     ($mod_row['attach_thumb_location'] != $mod_row['attach_location']) )
                                {
                                    $image_link = "{$this->ipsclass->vars['upload_url']}/{$mod_row['attach_thumb_location']}";

                                    // Yippie, our thumbnail is already made for us :)
                                    $gallery_mod_images .= $this->ipsclass->compiled_templates['skin_registry_gallery']->gallery_item_thumb(
                                                                array( 'filename' => $image_link,
                                                                       'title'    => $mod_row['attach_file'],
                                                                       'hits'     => $mod_row['attach_hits'],
                                                                       'type'     => 'registry_mod',
                                                                       'id'       => $mod_row['id'],
                                                              )      );
                                }
                                else
                                {
                                    // Since we don't have a pre-made thumb we are going
                                    //   to fall back on the old style :(

                                    $img_size = array();

                                    // Is this a remote image?
                                    if ( $mod_row['attach_thumb_location'] == "remote" )
                                    {
                                        $img_size = @GetImageSize( $mod_row['attach_location'] );
                                    }
                                    else
                                    {
                                        $img_size = @GetImageSize( $this->ipsclass->vars['upload_url']."/".$mod_row['attach_location'] );
                                    }

                                    if ( $img_size[0] < 1 )
                                    {
                                        $img_size    = array();
                                        $img_size[0] = $this->registry_config['thumbnail_resolution'] + 1;
                                        $img_size[1] = $this->registry_config['thumbnail_resolution'] + 1;
                                    }

                                    // Form the correct image link if it's remote
                                    $image_link = ($mod_row['attach_thumb_location'] == "remote")
                                                ? $mod_row['attach_location']
                                                : "{$this->ipsclass->vars['upload_url']}/{$mod_row['attach_location']}";

                                    //----------------------------------------------------
                                    // Do we need to scale?
                                    //----------------------------------------------------

                                    if ( ( $img_size[0] <= $this->registry_config['thumbnail_resolution'] ) AND
                                         ( $img_size[1] <= $this->registry_config['thumbnail_resolution'] ) )
                                    {
                                        $gallery_mod_images .= $this->ipsclass->compiled_templates['skin_registry_gallery']->gallery_item_thumb(
                                                                    array( 'filename' => $image_link,
                                                                           'title'    => $mod_row['attach_file'],
                                                                           'hits'     => $mod_row['attach_hits'],
                                                                           'type'     => 'registry_mod',
                                                                           'id'       => $mod_row['id'],
                                                                 )      );
                                    }
                                    else
                                    {
                                        $im = $this->ipsclass->scale_image( array( 'max_width'  => $this->registry_config['thumbnail_resolution'],
                                                                                   'max_height' => $this->registry_config['thumbnail_resolution'],
                                                                                   'cur_width'  => $img_size[0],
                                                                                   'cur_height' => $img_size[1]
                                                                          )      );

                                        $gallery_mod_images .= $this->ipsclass->compiled_templates['skin_registry_gallery']->gallery_item(
                                                                    array( 'filename' => $image_link,
                                                                           'title'    => $mod_row['attach_file'],
                                                                           'width'    => $im['img_width'],
                                                                           'height'   => $im['img_height'],
                                                                           'hits'     => $mod_row['attach_hits'],
                                                                           'type'     => 'registry_mod',
                                                                           'id'       => $mod_row['id'],
                                                                  )      );
                                    }
                                }
                            } // End if image
                            else
                            {
                                // This appears to be a non-image attachment, let's show it!
                                $gallery_mod_images .= $this->ipsclass->compiled_templates['skin_registry_core']->show_attachments(
                                                            array( 'image' => $this->ipsclass->cache['attachtypes'][ $mod_row['attach_ext'] ]['atype_img'],
                                                                   'name'  => $mod_row['attach_file'],
                                                                   'id'    => $mod_row['id'],
                                                                   'type'  => 'registry_mod',
                                                          )      );
                            }
                        } // END if limit
                    }
                    // END vehicle gallery addition
                }

                // Output the HTML
                $mod_list .= $this->ipsclass->compiled_templates['skin_registry_item']->mod_view_category_row($mod_row);
            }

            // Now let's build the category table
            $cat_row['mod_list'] = $mod_list;
            $mods_html .= $this->ipsclass->compiled_templates['skin_registry_item']->mod_view_category($cat_row);
        }

        // Now let's finish off the mod pictures gallery if we have
        //   found any images.
        if ( $mod_images_found )
        {
            // Prepend the header
            if ($this->registry_config['limit_mod_gallery'])
            {
                $start_range = ($mod_images_found < $this->registry_config['limit_mod_gallery_amount']) ? $mod_images_found : $this->registry_config['limit_mod_gallery_amount'];

                $t_array['image_limit'] = '<i>('. $start_range .' '. $this->ipsclass->lang['out_of'] .' '. $mod_images_found .' '. $this->ipsclass->lang['total'] .' '. $this->ipsclass->lang['shown'] .')</i>';
            }

            $gallery_mod_images = $this->ipsclass->compiled_templates['skin_registry_gallery']->gallery_mod_header($t_array) . $gallery_mod_images;

            // Append the footer
            $gallery_mod_images .= $this->ipsclass->compiled_templates['skin_registry_gallery']->gallery_section_footer();

            // Add this section to the gallery
            $gallery_sections['mod_pictures'] = $gallery_mod_images;
        }
        else
        {
            // If we don't have any mod images, we aren't going
            //   to show this section.
            $gallery_sections['mod_pictures'] = '';
        }

        // Prepare the gallery HTML
        if ($mod_images_found OR $vehicle_images_found == TRUE)
        {
            $vehicle_data['gallery'] = $this->ipsclass->compiled_templates['skin_registry_gallery']->view($gallery_sections);
        }

        // Prepare the mods HTML for the big picture
        $vehicle_data['mods'] = $mods_html;

        // Let's compile their guestbook summary if it's enabled
        if ($this->registry_config['enable_guestbooks'] == 1)
        {
            // Setup parser
            $this->lib['parser']->parse_smilies = $this->registry_config['allow_bbcode_gb'];
            $this->lib['parser']->parse_bbcode  = $this->registry_config['allow_bbcode_gb'];
            $this->lib['parser']->parse_html    = $this->registry_config['allow_html_gb'];
            $this->lib['parser']->parse_nl2br   = 1;

            // Get the total count of comments
            $guestbook_id = $this->ipsclass->DB->query("SELECT count(*) as total FROM ibf_registry_guestbooks
                                                        WHERE ibf_registry_guestbooks.item_id = '". $this->ipsclass->input['CID'] ."'");

            $guestbook_count = $this->ipsclass->DB->fetch_row($guestbook_id);

            $guestbook_id = $this->ipsclass->DB->query("SELECT gb.post, gb.author_id, m.members_display_name
                                                        FROM ibf_registry_guestbooks AS gb
                                                            LEFT JOIN ibf_members AS m ON gb.author_id = m.id
                                                        WHERE gb.item_id = '". $this->ipsclass->input['CID'] ."'
                                                        ORDER BY gb.post_date DESC LIMIT 5");

            $guestbook = array();
            while ( $guestbook_msg = $this->ipsclass->DB->fetch_row($guestbook_id) )
            {
                // Parse it out
                $guestbook_msg['post'] = $this->lib['parser']->pre_edit_parse( $guestbook_msg['post'] );

                if ( strlen($guestbook_msg['post']) >= 75 )
                {
                    // If this is a long message append some dots
                    $guestbook_msg['post'] = substr( $guestbook_msg['post'], 0, 75) . '...';
                }

                // Was this a guest?
                if ( empty( $guestbook_msg['members_display_name'] ) )
                {
                    $guestbook['messages'] = "{$this->ipsclass->lang['guest']}: {$guestbook_msg['post']}<br />" . $guestbook['messages'];
                }
                else
                {
                    $guestbook['messages'] = "<a href='{$this->ipsclass->base_url}&amp;showuser={$guestbook_msg['author_id']}'>{$guestbook_msg['members_display_name']}</a>: {$guestbook_msg['post']}<br />" . $guestbook['messages'];
                }
            }

            // Pass along the vihicle id to the guestbook
            $guestbook['CID'] = $this->ipsclass->input['CID'];

            // Pass along the total count
            $guestbook['total'] = $guestbook_count['total'];

            // Prepare the guestbook HTML
            $vehicle_data['guest_book_summary'] = $this->ipsclass->compiled_templates['skin_registry_item']->guestbook_summary($guestbook);
        }

        // Go get all our custom fields data
        $cf_data = $this->lib['custom_fields']->process_cf( array( 'type' => 'view', 'CID' => $vehicle_data['id'] ) );

        $vehicle_data['custom_fields'] = $cf_data['html'];

        // Setup our highlight for the title
        $cf_highlight = $this->lib['custom_fields']->get_cf_highlight();

        $vehicle_data['highlight_field_value'] = '';

        foreach ( $cf_highlight as $cf_field_id => $cf_highlight_row )
        {
            $vehicle_data['highlight_field_value'] .= $this->lib['custom_fields']->process_cf_value( array( 'def' => $cf_highlight_row,
                                                                                                            'value' => $cf_data['cf_entries'][$cf_field_id]['field_value'],
                                                                                                            'type' => 'view',
                                                                                                   )      );
            // Append space for readability
            $vehicle_data['highlight_field_value'] .= ' ';
        }

        // Go get our overall ratings if they are enabled
        if ( $this->registry_config['enable_item_ratings'] == 1 )
        {
            $rating_report = $this->lib['ratings']->get_rating_report( $this->ipsclass->input['CID'] );

            // Only create output if there are ratings defined
            if ( !empty($rating_report) )
            {
                $ratings_html = '';

                foreach ( $rating_report as $rating_id => $rating_row )
                {
                    $ratings_html .= $this->ipsclass->compiled_templates['skin_registry_item']->view_rating_row( array( 'rating_name' => $rating_row['rating_name'],
                                                                                                                        'rating_image' => $rating_row['rating_image'],
                                                                                                               )      );
                }

                // Plug it into the big picture
                $vehicle_data['overall_ratings'] = $this->ipsclass->compiled_templates['skin_registry_item']->overall_ratings( array( 'ratings' => $ratings_html,
                                                                                                                                      'item_id' => $this->ipsclass->input['CID'],
                                                                                                                             )      );
            }
        }

        // Get our fancy javascript
        $vehicle_data['popup_javascript'] = $this->ipsclass->compiled_templates['skin_registry_core']->popup_javascript();

        // Set page title
        $this->page_title = $vehicle_data['members_display_name'] ."'s ". $vehicle_data['highlight_field_value'];

        // Add to our Nav Bar
        $this->nav_bar[] = "<a href='{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=browse'>{$this->ipsclass->lang['browse']}</a>";


        // wOOt, there it is!
        return $this->ipsclass->compiled_templates['skin_registry_item']->view($vehicle_data);
    }
}